package com.jzlx.utils;

import java.net.*;
import java.util.*;

/**
 * @description:
 * @author: zhulei
 * @create: 2025-03-24 15:43
 **/
public class IpUtil {
    public static String getLocalIp() {
        String ip = "";
        try {
            // 获取本机的InetAddress对象
            InetAddress localHost = InetAddress.getLocalHost();

            // 获取本机的IP地址
            ip = localHost.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return ip;
    }

    public static List<String> getLocalIPv4s() {
        List<String> ipList = null;
        try {
            ipList = new ArrayList<>();
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface ni = interfaces.nextElement();
                if (ni.isLoopback() || ni.isVirtual() || !ni.isUp()) {
                    continue;
                }
                Enumeration<InetAddress> addresses = ni.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress addr = addresses.nextElement();
                    if (addr instanceof Inet4Address) {
                        ipList.add(addr.getHostAddress());
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        System.out.println(Arrays.deepToString(ipList.toArray()));
        return ipList;
    }

}
